import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wayofdressing/contraints.dart';
import 'package:wayofdressing/components/inmenubutton.dart';
import 'package:wayofdressing/dio/OutfitDio.dart';
import 'package:wayofdressing/vivo_connect.dart';
import 'package:wayofdressing/all_information/user_information.dart';
import 'package:wayofdressing/dio/configureDio.dart';

class AiDressScreen extends StatefulWidget {
  static String id = 'aidressscreen';

  @override
  State<AiDressScreen> createState() => _AiDressScreenState();
}

class _AiDressScreenState extends State<AiDressScreen> {
  IconData _actionIcon = Icons.favorite_border_rounded;
  int _currentPageIndex = 0;
  String weather = '...';
  String aiSuggestion = '';
  List<Widget> outfits = [];
  Map<String, List<String>> outfitsInfo = {
    'name': ['无搭配,请添加搭配!'],
    'description': ['无搭配,请添加搭配!'],
    'category': ['无搭配,请添加搭配!']
  };
  Color loveColor = Colors.black;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getWeatherAndAiDresses();
  }

  _buildPageViewItem(String name, String description) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(25),
        color: Color(0xfffffaf0),
      ),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '搭配名称: ${name ?? ''}',
              style: TextStyle(color: Colors.black, fontSize: 18),
            ),
            Text(
              '搭配描述: ${description ?? ''}',
              style: TextStyle(color: Colors.black, fontSize: 16),
            )
          ],
        ),
      ),
    );
  }

  Future<void> _getWeatherAndAiDresses() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String savedAiSuggestion = prefs.getString('AiChooseOutfit') ?? '';
    DateTime now = DateTime.now();
    String currentDateString = '${now.year}-${now.month}-${now.day}';
    String cachedDateString = prefs.getString('cachedDate') ?? '';
    Response response = await getOutfitByUserId(userId: userId, dio: dio);
    dynamic data = response.data['data'];
    if (response.data['success'] == true) {
      if (savedAiSuggestion == '' || currentDateString != cachedDateString) {
        weather = prefs.getString('weather') ?? '';
        savedAiSuggestion = await vivogpt(
            '这是我已经有的几套衣服穿搭搭配的信息和今天的天气,天气:$weather,衣服的搭配:$data,请你帮我选择用哪个搭配比较好，告诉我对应的name后面的名字即可，如果衣服搭配为空则告诉我天气和大致搭配的方向即可。');
        setState(() {
          aiSuggestion = savedAiSuggestion;
        });
        prefs.setString('AiChooseOutfit', aiSuggestion);
      } else {
        setState(() {
          aiSuggestion = savedAiSuggestion;
        });
      }
      for (dynamic item in data) {
        outfitsInfo['name']?.add(item['name']);
        outfitsInfo['description']?.add(item['description']);
        outfitsInfo['category']?.add(item['category']);
      }
      if (outfitsInfo['name']!.length > 1) {
        outfitsInfo['name']?.removeAt(0);
        outfitsInfo['description']?.removeAt(0);
        outfitsInfo['category']?.removeAt(0);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffffaf0),
      appBar: AppBar(
        backgroundColor: Color(0xfffffaf0),
        elevation: 0,
        toolbarHeight: 80,
        leadingWidth: 100,
        centerTitle: true,
        title: Text(
          'AI搭',
          style: TextStyle(
            color: Colors.black,
            fontWeight: FontWeight.bold,
            fontSize: kTopTitleFontSize,
          ),
        ),
        leading: Row(
          children: [
            SizedBox(
              width: 10,
            ),
            GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: Transform.scale(
                scaleX: -1,
                child: Icon(
                  Icons.play_arrow_rounded,
                  size: kAppBarButtonSize,
                  color: Colors.black.withOpacity(0.5),
                ),
              ),
            ),
          ],
        ),
        actions: [
          MenuAnchor(
            menuChildren: [
              InMenuButton(
                onPressed: () {},
                text: '历史搭配',
                alignment: Alignment.centerRight,
              ),
            ],
            style: MenuStyle(
              shape: MaterialStateProperty.all(
                RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.0),
                ),
              ),
              alignment: Alignment(-3, 0.5),
              padding: MaterialStateProperty.all(EdgeInsets.all(15.0)),
              shadowColor: MaterialStateProperty.all(Colors.transparent),
              backgroundColor: MaterialStateProperty.all(
                Colors.black.withOpacity(0.4),
              ),
            ),
            builder: (BuildContext context, MenuController controller,
                Widget? child) {
              return GestureDetector(
                onTap: () {
                  if (controller.isOpen) {
                    controller.close();
                  } else {
                    controller.open();
                  }
                },
                child: Icon(
                  Icons.calendar_today_rounded,
                  size: kAppBarButtonSize,
                  color: Colors.black,
                ),
              );
            },
          ),
          SizedBox(
            width: 20,
          )
        ],
      ),
      body: Container(
        margin: EdgeInsets.symmetric(horizontal: 30),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Expanded(
              flex: 2,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Row(
                    children: [
                      CircleAvatar(
                        backgroundImage: AssetImage('images/peanut.jpg'),
                      )
                    ],
                  ),
                  Expanded(
                    child: Container(
                      margin: EdgeInsets.only(left: 10,bottom: 20),
                      padding: EdgeInsets.all(20),
                      decoration: BoxDecoration(
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.2), // 阴影颜色和透明度
                              spreadRadius: 2, // 阴影扩展半径
                              blurRadius: 5, // 阴影模糊半径
                              offset: Offset(0, 5), // 阴影偏移量
                            ),
                          ],
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(25)),
                      child: ListView(
                        children: [
                          Text(
                            aiSuggestion,
                            style: TextStyle(color: Colors.black, fontSize: 12),
                            softWrap: true,
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              flex: 7,
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.2), // 阴影颜色和透明度
                      spreadRadius: 2, // 阴影扩展半径
                      blurRadius: 5, // 阴影模糊半径
                      offset: Offset(0, 5), // 阴影偏移量
                    ),
                  ],
                  borderRadius: BorderRadius.circular(25),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                        margin: EdgeInsets.only(left: 18, top: 12),
                        child: Text(
                            '搭配类别: ${outfitsInfo['category']![_currentPageIndex]}')),
                    Expanded(
                      child: Container(
                        margin:
                            EdgeInsets.symmetric(horizontal: 20, vertical: 30),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.2), // 阴影颜色和透明度
                              spreadRadius: 2, // 阴影扩展半径
                              blurRadius: 5, // 阴影模糊半径
                              offset: Offset(0, 5), // 阴影偏移量
                            ),
                          ],
                          borderRadius: BorderRadius.circular(25),
                        ),
                        child: Stack(
                          children: <Widget>[
                            PageView.builder(
                              onPageChanged: (int index) {
                                setState(() {
                                  _currentPageIndex =
                                      index % (outfitsInfo['name']!.length);
                                });
                              },
                              itemCount: 10000,
                              itemBuilder: (context, index) {
                                return _buildPageViewItem(
                                    outfitsInfo['name']![
                                        index % (outfitsInfo['name']!.length)],
                                    outfitsInfo['description']![
                                        index % (outfitsInfo['name']!.length)]);
                              },
                            ),
                            Positioned(
                              bottom: 10,
                              left: 0,
                              right: 0,
                              child: Container(
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: List.generate(
                                      outfitsInfo['name']!.length, (i) {
                                    return Container(
                                      margin:
                                          EdgeInsets.symmetric(horizontal: 5),
                                      width: _currentPageIndex == i ? 32 : 25,
                                      height: _currentPageIndex == i ? 32 : 25,
                                      decoration: BoxDecoration(
                                          shape: _currentPageIndex == i
                                              ? BoxShape.circle
                                              : BoxShape.rectangle,
                                          color: _currentPageIndex == i
                                              ? Colors.white
                                              : Colors.black),
                                      child: Center(
                                        child: Text(
                                          '${_currentPageIndex + 1}',
                                          style: TextStyle(
                                              fontSize: 18,
                                              fontWeight: FontWeight.bold),
                                        ),
                                      ),
                                    );
                                  }).toList(),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ),
            Expanded(
                child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                AnimatedSwitcher(
                  transitionBuilder: (child, anim) {
                    return ScaleTransition(child: child, scale: anim);
                  },
                  duration: Duration(milliseconds: 350),
                  child: IconButton(
                    iconSize: 52,
                    key: ValueKey(_actionIcon),
                    icon: Icon(
                      _actionIcon,
                      color: loveColor,
                    ),
                    onPressed: () {
                      setState(
                        () {
                          if (_actionIcon == Icons.favorite_border_rounded) {
                            _actionIcon = Icons.favorite_rounded;
                            loveColor = Colors.pink;
                          } else {
                            _actionIcon = Icons.favorite_border_rounded;
                            loveColor = Colors.black;
                          }
                        },
                      );
                    },
                  ),
                ),
              ],
            )),
          ],
        ),
      ),
    );
  }
}
